// login & register
const express = require("express")
const router = express.Router()
const bcrypt = require("bcryptjs")
const jwt = require("jsonwebtoken")
const gravatar = require("gravatar")
const User = require("../../models/users")
const keys = require("../../config/keys").secretOrKey
const passport = require("passport")

// $route get 请求路径：api/users/test
// @desc 返回请求的json数据
// @access 是否公开
router.get("/test", (req, res) => {
  res.json("login success")
})

// register 注册接口
// @desc
// @access Public
router.post("/register", (req, res) => {
  // 查询数据库里面有没有存在邮箱
  User.findOne({
    email: req.body.email
  }).then(user => {
    if (user) {
      return res.status(400).json("邮箱已经被占用！")
    } else {
      var avatar = gravatar.url(req.body.email, { s: '200', r: 'pg', d: 'mm' });
      const newUser = new User({
        name: req.body.name,
        email: req.body.email,
        avatar,
        password: req.body.password,
        identity: req.body.identity, // 权限
      })

      bcrypt.genSalt(10, function (err, salt) {
        bcrypt.hash(newUser.password, salt, (err, hash) => {
          if (err) {
            throw err
          }
          newUser.password = hash

          newUser.save().then(user => {
            res.json(user)
          }).catch(err => {
            console.log(err)
          })
        })
      })
    }
  }).catch(err => {
    console.log(err)
  })
})

// POST api/user/login 登录
// @desc 返回token jwt password
// @access Public
router.post("/login", (req, res) => {
  const email = req.body.email
  const password = req.body.password

  // 登录校验
  User.findOne({ email }).then(user => {
    if (!user) {
      return res.status(404).json("用户不存在！")
    }

    // 密码匹配
    bcrypt.compare(password, user.password).then(isMatch => {
      if (isMatch) {
        // 生产jwt
        const rule = {
          id: user.id,
          name: user.name,
          avatar: user.avatar,
          identity: user.identity
        };
        jwt.sign(rule, keys, { expiresIn: 3600 }, (err, token) => {
          if (err) {
            return;
          }
          res.json({
            success: true,
            token: `Bearer ${token}`
          })
        })
      } else {
        return res.status(400).json("密码错误！")
      }
    })
  })
})

// GET api/users/getInfo
// @desc 验证token通过之后，返回当前用户信息
// @access Private
router.get("/getInfo", passport.authenticate("jwt", { session: false }), (req, res) => {
  res.json({
    id: req.user.id,
    name: req.user.name,
    email: req.user.email,
    avatar: req.user.avatar,
    identity: req.user.identity
  })
})

module.exports = router